package com.millstein.realtime.app.dws;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.PropertyNamingStrategy;
import com.alibaba.fastjson.serializer.SerializeConfig;
import com.millstein.realtime.app.base.BaseAppV1;
import com.millstein.realtime.app.func.DimAsyncFunction;
import com.millstein.realtime.bean.TradeTrademarkCategoryUserRefundBean;
import com.millstein.realtime.common.Constants;
import com.millstein.realtime.util.CommonUtil;
import com.millstein.realtime.util.FlinkSinkUtil;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.streaming.api.datastream.AsyncDataStream;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.windowing.ProcessWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

import java.time.Duration;
import java.util.Collections;
import java.util.HashSet;
import java.util.concurrent.TimeUnit;

/**
 * @Description
 * @Author tsing
 * @Date 2024-11-01 10:10
 */
public class Dws_11_TradeTrademarkCategoryUserRefundWindow extends BaseAppV1 {

    public static void main(String[] args) {
        new Dws_11_TradeTrademarkCategoryUserRefundWindow().init(
                8011,
                3,
                "Dws_11_TradeTrademarkCategoryUserRefundWindow",
                Constants.TOPIC_DWD_TRADE_ORDER_REFUND
        );
    }

    /**
     * 具体数据处理的逻辑，由子类编写
     *
     * @param env          执行环境对象
     * @param streamSource 待处理的数据流
     */
    @Override
    protected void handle(StreamExecutionEnvironment env, DataStreamSource<String> streamSource) {
        // 构建退单数据明细
        SingleOutputStreamOperator<TradeTrademarkCategoryUserRefundBean> refundStream = buildRefundData(streamSource);
        // 补充聚合维度
        SingleOutputStreamOperator<TradeTrademarkCategoryUserRefundBean> dimFullStream = supplementAggregateDim(refundStream);
        // 窗口聚合
        SingleOutputStreamOperator<TradeTrademarkCategoryUserRefundBean> aggregateStream = windowAndAgg(dimFullStream);
        // 补充其他维度
        SingleOutputStreamOperator<TradeTrademarkCategoryUserRefundBean> resultStream = supplementOtherDim(aggregateStream);
        // 将处理完的数据写到doris中
        writeToDoris(resultStream);
    }

    /**
     * 构建退单数据
     * @param streamSource 待构建的数据流
     * @return
     */
    private SingleOutputStreamOperator<TradeTrademarkCategoryUserRefundBean> buildRefundData(
            DataStreamSource<String> streamSource
    ) {
        return streamSource
                .map(new MapFunction<String, TradeTrademarkCategoryUserRefundBean>() {
                    @Override
                    public TradeTrademarkCategoryUserRefundBean map(String value) throws Exception {
                        JSONObject json = JSONObject.parseObject(value);
                        return TradeTrademarkCategoryUserRefundBean.builder()
                                .orderIdSet(new HashSet<String>(Collections.singleton(json.getString("order_id"))))
                                .skuId(json.getString("sku_id"))
                                .userId(json.getString("user_id"))
                                .ts(json.getLong("ts") * 1000)
                                .build();
                    }
                });
    }

    /**
     * 补充聚合维度。因为统计的维度中有品牌和品类，都必须从dim_sku_info中获取，所以要先补充，然后再窗口计算
     * @param refundStream 待补充维度的数据流
     * @return
     */
    private SingleOutputStreamOperator<TradeTrademarkCategoryUserRefundBean> supplementAggregateDim(
            SingleOutputStreamOperator<TradeTrademarkCategoryUserRefundBean> refundStream
    ) {
        return AsyncDataStream.unorderedWait(
                refundStream,
                new DimAsyncFunction<TradeTrademarkCategoryUserRefundBean>() {
                    @Override
                    protected String getTableName() {
                        return "dim_sku_info";
                    }

                    @Override
                    protected String getId(TradeTrademarkCategoryUserRefundBean input) {
                        return input.getSkuId();
                    }

                    @Override
                    protected void supplementDim(TradeTrademarkCategoryUserRefundBean bean, JSONObject dim) {
                        bean.setTrademarkId(dim.getString("TM_ID"));
                        bean.setCategory3Id(dim.getString("CATEGORY3_ID"));
                    }
                },
                30,
                TimeUnit.SECONDS,
                50
        );
    }

    /**
     * 窗口计算
     * @param refundStream 待计算的数据流
     * @return
     */
    private SingleOutputStreamOperator<TradeTrademarkCategoryUserRefundBean> windowAndAgg(
            SingleOutputStreamOperator<TradeTrademarkCategoryUserRefundBean> refundStream
    ) {
        return refundStream
                .assignTimestampsAndWatermarks(
                        WatermarkStrategy
                                .<TradeTrademarkCategoryUserRefundBean>forBoundedOutOfOrderness(Duration.ofSeconds(3))
                                .withTimestampAssigner(((element, recordTimestamp) -> element.getTs()))
                )
                .keyBy(item -> item.getUserId()
                        + "_" + item.getTrademarkId()
                        + "_" + item.getCategory3Id())
                .window(TumblingEventTimeWindows.of(Time.seconds(5)))
                .reduce(
                        new ReduceFunction<TradeTrademarkCategoryUserRefundBean>() {
                            @Override
                            public TradeTrademarkCategoryUserRefundBean reduce(
                                    TradeTrademarkCategoryUserRefundBean bean1,
                                    TradeTrademarkCategoryUserRefundBean bean2
                            ) throws Exception {
                                bean1.getOrderIdSet().addAll(bean2.getOrderIdSet());
                                return bean1;
                            }
                        },
                        new ProcessWindowFunction<TradeTrademarkCategoryUserRefundBean, TradeTrademarkCategoryUserRefundBean, String, TimeWindow>() {
                            @Override
                            public void process(
                                    String key,
                                    Context context,
                                    Iterable<TradeTrademarkCategoryUserRefundBean> elements,
                                    Collector<TradeTrademarkCategoryUserRefundBean> out
                            ) throws Exception {
                                TradeTrademarkCategoryUserRefundBean bean = elements.iterator().next();
                                String startTime = CommonUtil.formatTime(context.window().getStart());
                                String endTime = CommonUtil.formatTime(context.window().getEnd());
                                String curDate = startTime.substring(0, 10);
                                bean.setStt(startTime);
                                bean.setEdt(endTime);
                                bean.setCurDate(curDate);
                                bean.setRefundCount((long) bean.getOrderIdSet().size());
                                out.collect(bean);
                            }
                        }
                );
    }

    /**
     * 补充其他维度
     * @param aggregateStream 计算后的数据流
     * @return
     */
    private SingleOutputStreamOperator<TradeTrademarkCategoryUserRefundBean> supplementOtherDim(
            SingleOutputStreamOperator<TradeTrademarkCategoryUserRefundBean> aggregateStream
    ) {
        SingleOutputStreamOperator<TradeTrademarkCategoryUserRefundBean> tmStream = AsyncDataStream.unorderedWait(
                aggregateStream,
                new DimAsyncFunction<TradeTrademarkCategoryUserRefundBean>() {
                    @Override
                    protected String getTableName() {
                        return "dim_base_trademark";
                    }

                    @Override
                    protected String getId(TradeTrademarkCategoryUserRefundBean input) {
                        return input.getTrademarkId();
                    }

                    @Override
                    protected void supplementDim(TradeTrademarkCategoryUserRefundBean bean, JSONObject dim) {
                        bean.setTrademarkName(dim.getString("TM_NAME"));
                    }
                },
                30,
                TimeUnit.SECONDS,
                50
        );

        SingleOutputStreamOperator<TradeTrademarkCategoryUserRefundBean> category3Stream = AsyncDataStream.unorderedWait(
                tmStream,
                new DimAsyncFunction<TradeTrademarkCategoryUserRefundBean>() {
                    @Override
                    protected String getTableName() {
                        return "dim_base_category3";
                    }

                    @Override
                    protected String getId(TradeTrademarkCategoryUserRefundBean input) {
                        return input.getCategory3Id();
                    }

                    @Override
                    protected void supplementDim(TradeTrademarkCategoryUserRefundBean bean, JSONObject dim) {
                        bean.setCategory3Name(dim.getString("NAME"));
                        bean.setCategory2Id(dim.getString("CATEGORY2_ID"));
                    }
                },
                30,
                TimeUnit.SECONDS,
                50
        );

        SingleOutputStreamOperator<TradeTrademarkCategoryUserRefundBean> category2Stream = AsyncDataStream.unorderedWait(
                category3Stream,
                new DimAsyncFunction<TradeTrademarkCategoryUserRefundBean>() {
                    @Override
                    protected String getTableName() {
                        return "dim_base_category2";
                    }

                    @Override
                    protected String getId(TradeTrademarkCategoryUserRefundBean input) {
                        return input.getCategory2Id();
                    }

                    @Override
                    protected void supplementDim(TradeTrademarkCategoryUserRefundBean bean, JSONObject dim) {
                        bean.setCategory2Name(dim.getString("NAME"));
                        bean.setCategory1Id(dim.getString("CATEGORY1_ID"));
                    }
                },
                30,
                TimeUnit.SECONDS,
                50
        );

        return AsyncDataStream.unorderedWait(
                category2Stream,
                new DimAsyncFunction<TradeTrademarkCategoryUserRefundBean>() {
                    @Override
                    protected String getTableName() {
                        return "dim_base_category1";
                    }

                    @Override
                    protected String getId(TradeTrademarkCategoryUserRefundBean input) {
                        return input.getCategory1Id();
                    }

                    @Override
                    protected void supplementDim(TradeTrademarkCategoryUserRefundBean bean, JSONObject dim) {
                        bean.setCategory1Name(dim.getString("NAME"));
                    }
                },
                30,
                TimeUnit.SECONDS,
                50
        );
    }

    /**
     * 将数据写到doris中
     * @param resultStream 处理完的数据
     */
    private void writeToDoris(SingleOutputStreamOperator<TradeTrademarkCategoryUserRefundBean> resultStream) {
        resultStream
                .map(item -> {
                    SerializeConfig config = new SerializeConfig();
                    config.propertyNamingStrategy = PropertyNamingStrategy.SnakeCase;
                    return JSONObject.toJSONString(item, config);
                })
                .addSink(FlinkSinkUtil.getDorisSink("gmall.dws_trade_trademark_category_user_refund_window"));
    }
}
